package com.cykj.faceledtv.netty;


import android.support.annotation.NonNull;

import com.cykj.faceledtv.entity.NettyReceiverModel;
import com.cykj.faceledtv.entity.NettySendMsgModel;
import com.orhanobut.logger.Logger;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @author jzh
 * @date 2018/11/06 11:05
 */
public class NettyClientHandler extends SimpleChannelInboundHandler<NettyReceiverModel> {
    @NonNull
    private NettyListener listener;

    public NettyClientHandler(@NonNull NettyListener listener) {
        this.listener = listener;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        listener.onServiceStatusConnectChanged(NettyListener.STATUS_CONNECT_SUCCESS);
        Logger.d("NettyClientHandler 连接成功");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        listener.onServiceStatusConnectChanged(NettyListener.STATUS_CONNECT_CLOSED);
        Logger.e("NettyClientHandler 连接断开，尝试重连");
        NettyClient.getInstance().setChannel(null);
        NettyClient.getInstance().reconnect();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, NettyReceiverModel model) throws Exception {
        if (model == null) {
            return;
        }
        if (model.isHeart()) {
            Logger.d("接收到服务端心跳包回复");
            return;
        }
        if (model.getData() == null) {
            return;
        }
        listener.onMessageResponse(model);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        Logger.e(cause, "netty异常");
        if (ctx.channel() != null && ctx.channel().isActive()) {
            ctx.close();
            Logger.e("channel断开");
        }
    }

    /**
     * 心跳超时管理
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.WRITER_IDLE) {
                listener.onServiceStatusConnectChanged(NettyListener.STATUS_HEART_WHITE_TIME_OUT);
                Logger.e("心跳写超时");
            } else if (e.state() == IdleState.READER_IDLE) {
                listener.onServiceStatusConnectChanged(NettyListener.STATUS_HEART_READ_TIME_OUT);
                Logger.e("心跳读超时");
            } else {
                listener.onServiceStatusConnectChanged(NettyListener.STATUS_HEART_ALL_TIME_OUT);
                Logger.e("心跳读写超时");
            }
            if (ctx != null && ctx.channel() != null) {
                ctx.channel().close();
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
